/**
 *
 */
package pt.mleiria.bo.games;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import pt.mleiria.dao.UserDao;
import pt.mleiria.dao.playground.TabuadaScoreDao;
import pt.mleiria.vo.TabuadaScore;

/**
 * @author manuel
 *
 */
@Stateless
public class TabuadaScoreEJB {

    private static final Logger LOG = Logger.getLogger(TabuadaScoreEJB.class);

    @PersistenceContext(unitName = "DomusService")
    private EntityManager em;

    public boolean saveScore(final TabuadaScore ts) {
        try {
            TabuadaScoreDao tsDao = new TabuadaScoreDao();
            tsDao.setUserdao(findUserDao(ts.getUser_id()));
            tsDao.setScore(ts.getScore());
            tsDao.setScoretime(ts.getScoreTime());
            tsDao.setTotalQuestions(ts.getTotalQuestions());
            Calendar cal = Calendar.getInstance();
            tsDao.setCurrentDate(cal.getTime());
            em.persist(tsDao);
            return true;
        } catch (Exception e) {
            LOG.fatal("Error saving tabuada score:" + ts.toString());
            e.printStackTrace();
            return false;
        } finally {
            em.flush();
        }
    }

    public UserDao findUserDao(int id) {
        return em.find(UserDao.class, id);
    }

    public TabuadaScore[] getAllOfFame() {

        /*
         Query q = em
         .createQuery("select u, ts from UserDao u, TabuadaScoreDao ts where u.id = ts.user_id "
         + "order by ts.score desc ts.scoretime asc");
         */
        Query q = em
                .createQuery("select u from UserDao u ");
        //+ "order by u.tsDao.score desc, u.tsDao.scoretime asc");
        q.setMaxResults(10);
        List<UserDao> list = q.getResultList();

        List<TabuadaScore> tmpList = new ArrayList<TabuadaScore>();

        for (UserDao userDao : list) {
            if (!userDao.getTsDao().isEmpty()) {
                for (TabuadaScoreDao tsd : userDao.getTsDao()) {
                    final TabuadaScore tscore = new TabuadaScore();
                    tscore.setUsername(userDao.getUsername());
                    tscore.setScore(tsd.getScore());
                    tscore.setScoreTime(tsd.getScoretime());
                    tscore.setTotalQuestions(tsd.getTotalQuestions());
                    tscore.setUser_id(userDao.getId());
                    tscore.setTs(tsd.getCurrentDate());
                    tmpList.add(tscore);
                }
            }
        }
        final TabuadaScore[] ts = tmpList.toArray(new TabuadaScore[tmpList.size()]);
        Arrays.sort(ts);
        return ts;
    }

}
